local nfs   = require "nixio.fs"
local json = require "luci.jsonc"

require"luci.sys"
m=SimpleForm("nwt",translate("添加设备"))
m.redirect=luci.dispatcher.build_url("admin/nwt/device")
m.reset=false
newname=m:field(Value,"_devicename","新设备名称",
"15个字符以内，允许: <code>A-Z</code>, <code>a-z</code>, <code>0-9</code> 和 <code>_</code>"
)
newname.datatype="and(uciname,maxlength(15))"

newaddr=m:field(Value,"_deviceaddr","新设备地址码",
"6位数字，如010203")
newaddr.datatype="and(digit,rangelength(6,6))"

function newaddr.validate(o,a,e)
	local addr=newaddr:formvalue(e)
	if addr and#addr>0 then
		local nwtconf = json.parse(nfs.readfile("/etc/nwt.json") or "")
		if type(nwtconf) == "table" and nwtconf.devices then
			for _,value in pairs(nwtconf.devices) do
				if addr == value.address then
					return nil,"设备已经存在"
				end
			end
		end
	end
	return a
end

function newaddr.write(e,a,n)
	local addr=newaddr:formvalue(a)
	if addr and#addr>0 then
		local devname=newname:formvalue(a)
		local nwtconf = json.parse(nfs.readfile("/etc/nwt.json") or "")
        if type(nwtconf) == "table" and nwtconf.devices then
			local deviceinfo = nwtconf.devices
        	deviceinfo[#deviceinfo+1] = {name=devname,address=addr}
        	local js = json.stringify(nwtconf)
			nfs.writefile("/etc/nwt.json",js)
        else
			if nwtconf then
        		nwtconf.devices = {{name=devname,address=addr}}
    		else
    			nwtconf = {devices={{name=devname,address=addr}}}
			end
        	local js = json.stringify(nwtconf)
			
			nfs.writefile("/etc/nwt.json",js)
        end
        --TODO restart serial client
		luci.sys.call("/etc/init.d/nwt restart")
        luci.http.redirect(luci.dispatcher.build_url("admin/nwt/device"))
	end
end

return m

